Ext.namespace("Dudley");
Ext.namespace("Dudley.lims");

Dudley.lims.Crossing = function() {

    var myCrossingData = [];
    var crossingForm = {};
    var crossingPanel = {};
    var crossingHash = null;
    var crossingCount = null;
    var crossingMaxNum = null;
    var crossingStore = null;
    var crossingLoaded = false;
    var searchInput = 'YCR';
    var searchOption = 'ycrKey';
    var pagingBar = null;
    var spotlightMenu = sptlght.utils.SpotlightUtils.getSpotlightMenu("ycrspotlightmenuid");

    function initCrossingStore(failedCb, callback) {
        loadCrossingSearchResult(0, null, callback);
    }

    function loadCrossingSearchResult(index, searchResultJSON, callback) {
   	    crossingStore = loadSolrSearchResult("YCR", getCrossingPagingColumns(), crossingSolrTranslator, index, searchResultJSON);
       	crossingStore.load({params:{start:0, limit:25}}, callback());
    }

    function goSearch(index, crossingSearchInput, crossingSearchOption) {
         if (crossingSearchInput == "") {
                        crossingSearchInput = 'YCR*';
         }
         var searchUrl = getSolrSearchUrl(getLuceneTerm("ycrFields",crossingSearchInput), 1000, ycrFields);
         var searchWin = getSearchLoadingWindow("ycr-");
         searchWin.on("show", function () {
            var sb = Ext.getCmp("ycr-search-statusbar");
            sb.showBusy();
        });
        searchWin.show();
        Ext.Ajax.request({
            url: searchUrl,
            method: "GET",
            success: function(response) {
                var searchResultObj = Ext.util.JSON.decode(response.responseText);
                eventManager.fireStatusMessageEvent({ text: "Crossing Search Results Count:" + searchResultObj.response.numFound, level: "info" });
                myCrossingData = [];
                loadCrossingSearchResult(index, searchResultObj.response, function() {
                    Ext.getDom("sample-search-result-list").innerHTML = "";
                    Ext.getDom("yo-form").innerHTML = "";
                    searchWin.close();
                    renderCrossingSearchResult();
                });
            },
            failure: function() {
                eventManager.fireStatusMessageEvent({ text: "Search Results failed for url:" + searchUrl, level: "error" });
            }
        });
    }

    function loadCrossingPanel() {
        var crossingSearchForm = getSearchForm("crossingSearchButtonId", "crossingSearchInputId", null);
        Ext.getCmp("crossingSearchButtonId").addListener("click", function(){
    			goSearch(0, Ext.getCmp("crossingSearchInputId").getValue(), "ycrFields");
    	   });
        var tbarButtons = [
            {
                id: 'showCrossingSearchResultsId',
                name: 'showCrossingSearchResults',
                disabled: true,
                text: 'Search Results',
                icon: "images/back-green.png",
                cls:'x-btn-text-icon',
                listeners: {click:
                        function() {
                            Ext.getDom("yo-form").innerHTML = "";
                            renderCrossingSearchResult();
                        }
                }
            },
            {
                id: 'searchAllCrossingId',
                name: 'searchAllCrossing',
                disabled: false,
                text: 'View All Records',
                icon: "images/search-blue.png",
                cls:'x-btn-text-icon',
                listeners: {click:
                        function() {
                            Ext.getDom("yo-form").innerHTML = "";
                            goSearch(0, 'YCR', 'ycrKey');
                        }
                }
            },
            {
                id: 'createNewCrossingId',
                name: 'createNewCrossing',
                text: 'Create New Crossing',
                icon: "images/add-green.png",
                cls:'x-btn-text-icon',
                listeners: {click:
                        function() {
                            Dudley.lims.Crossing.loadNewCrossing();
                        }
                }
            }
        ];
        crossingPanel = new Ext.Panel({
            id: "crossingPanelId",
            autoHeight: true,
            border: true,
            renderTo: "yad-panel",
            title: "Crossing",
            header: false,
            tbar: tbarButtons,
            items: crossingSearchForm
        });
        crossingPanel.on("activate", function () {
            Ext.getDom("yo-panel").innerHTML = "";
            Ext.getDom("yo-form").innerHTML = "";
            Ext.getDom("sample-search-result-list").innerHTML = "";
            if (crossingLoaded == false) {
                crossingLoaded = true;
                goSearch(0, searchInput, searchOption);
            }
            renderCrossingSearchResult();
        });
    }

    function postCrossingStrain(createNew) {
        var ycrKey = Ext.getCmp("crossingKeyId").getValue();
        var ycrPostJson = new Object();
        ycrPostJson["ycrKey"] = ycrKey;
        ycrPostJson["ycrAlias"] = Ext.getCmp("crossingAliasId").getValue();
        ycrPostJson["ycrType"] = Ext.getCmp("crossingTypeId").getValue();
        ycrPostJson["ycrParentA"] = Ext.getCmp("parentAId").getValue();
        ycrPostJson["ycrParentAlpha"] = Ext.getCmp("parentAlphaId").getValue();
        ycrPostJson["ycrTetradCt"] = Ext.getCmp("tetradCountId").getValue();
        ycrPostJson["ycrProgenyCt"] = Ext.getCmp("progenyCountId").getValue();
        ycrPostJson["ycrProgenyRange"] = Ext.getCmp("progenyRangeId").getValue();
        ycrPostJson["ycrSnps"] = Ext.getCmp("snpId").getValue();
        ycrPostJson["ycrSnpDupes"] = Ext.getCmp("snpDupeId").getValue();
        ycrPostJson["ycrDate"] = Ext.getCmp("crossingDateId").getRawValue();
        ycrPostJson["ycrPlates"] = Ext.getCmp("crossingPlatesId").getRawValue();
        ycrPostJson["ycrNotes"] = Ext.getCmp("crossingNoteId").getRawValue();
        var crossingCallback = function() {
                limsadmin_obj["limsadminCrossingCount"] = crossingCount;
                postSolrUpdates(limsadmin_obj, function(){
                    Ext.Msg.alert('Info', "New Crossing " + ycrKey + ' Added Successfully');
                    Ext.getDom("yo-form").innerHTML = "";
                    Ext.getDom("sample-search-result-list").innerHTML = "";
                    goSearch(0, ycrKey, "ycrKey");
                });
            };
            if (!createNew) {
                crossingCallback = function() {
                    Ext.Msg.alert('Info', ycrKey + ' Updated Successfully');
                    Ext.getDom("sample-search-result-list").innerHTML = "";
                    var searchResultsButton = Ext.getCmp("showCrossingSearchResultsId");
                    searchResultsButton.disable();
                };
            }
            postSolrUpdates(ycrPostJson, crossingCallback);
    }

    function loadCreateCrossingStrain(crossingHash, callback) {
        var createNew = true;
        var mergedSnp = false;
        var igvlink = "";
        var buttons = [
            {
                id: 'createButton',
                name: 'createButton',
                text: 'Create',
                listeners: {click:
                        function() {
                            if (validateCreateUpdateCrossing()) {
                                postCrossingStrain(createNew);
                            }
                        }
                }
            }
        ];
        if (crossingHash != null) {
                var viewProg = true;
                if (crossingHash.progenyCount != null && crossingHash.progenyCount != 0) {
                    viewProg = false;
                }
                buttons = [
                    {
                        id: 'updateCrossingButtonId',
                        name: 'updateCrossingButton',
                        text: 'Update',
                        listeners: {click:
                                function() {
                                    if (validateCreateUpdateCrossing()) {
                                        postCrossingStrain(!createNew);
                                    }
                                }
                        }
                    }
                ];
        } else {
            crossingHash = new Object();
            var crossingMaxInt = parseInt(crossingMaxNum);
            crossingMaxInt = crossingMaxInt + 1;
            var crossingCountInt = parseInt(crossingCount);
            crossingCountInt = crossingCountInt + 1;
            crossingCount = crossingCountInt + "";
            crossingHash.name = 'YCR' + crossingMaxInt;
            crossingMaxNum = crossingMaxInt + "";
            crossingHash.SNPs = 0;
            crossingHash.SNPDupes = 0;
            crossingHash.tetradCount = 0;
        }
        var disableSnp = true;
        if (crossingHash.parentA != null && crossingHash.parentA == "YO490" && crossingHash.parentAlpha == "YO512")
            disableSnp = false;
        if (crossingHash.crossingNote == null) {
            crossingHash.crossingNote = "";
        }
        if (crossingHash.crossingType == null) {
            crossingHash.crossingType = "NV";
        }
        if (crossingHash.progenyCount == null) {
            crossingHash.progenyCount = 0;
        }
        if (crossingHash.crossingPlates == null) {
            crossingHash.crossingPlates = "";
        }

        if (crossingHash.IGV != null && crossingHash.IGV == 'on') {
            mergedSnp = true;
            igvlink = "sequencing/igv/custom_config/" + crossingHash.name.replace(" ", "") + "_" + crossingHash.YCGSKeys + ":" + crossingHash.YCGSKey1 + ":" + crossingHash.YCGSKey2 + "/jnlp";
        }
        crossingForm = new Ext.form.FormPanel({
            id: 'crossingForm',
            method: 'POST',
            autoHeight: true,
            autoScroll: true,
            border: true,
            buttonAlign: 'left',
            tbar: [
                {
                id: 'createCrossingProgenyButtonId',
                text: 'Add Progeny Set',
                disabled: !createNew,
                icon: "images/check-green.png",
                cls:'x-btn-text-icon',
                tooltip: 'Create progeny',
                listeners: {
                    click:
                            function() {
                                getSolrLimsAdmin(function(limsadmin_obj) {
                                var maxypg = limsadmin_obj.limsadminYpgMaxNum;
                                var ycrYpgForm = new Ext.FormPanel({
                                frame:true,
                                title: 'Creating YPG for ' + crossingHash.name + " parentA:" + crossingHash.parentA + " parentAlpha:" + crossingHash.parentAlpha,
                                bodyStyle:'padding:5px 5px 0',
                                width: 450,
                                defaultType: "textfield",
                                items: [
                                {
                                    id: 'thisProgenyCountId',
                                    fieldLabel: 'Progeny count',
                                    listeners:{
                                        change: function(o,n){
                                            var newRange = (parseInt(maxypg) + 1) + ":" + (parseInt(maxypg) +parseInt(n));
                                            Ext.getCmp("thisProgenyRangeId").setValue(newRange);
                                            if (crossingHash.progenyCount != undefined && parseInt(crossingHash.progenyCount) > 0){
                                                var ypgsets = (crossingHash.progenyRange).split(",");
                                                var ypgsetNum = ypgsets.length + 1;
                                                /*var lastendrange = ypgsets[ypgsetNum-2].split(":")[1];
                                                if ((parseInt(maxypg) - 1) > lastendrange ){
                                                    Ext.getCmp("thisProgenyRangeId").setValue(crossingHash.progenyRange + "," + newRange);
                                                }else{
                                                    newRange = ypgsets[0].split(":")[0] + ":" + (parseInt(maxypg) +parseInt(n));
                                                    Ext.getCmp("thisProgenyRangeId").setValue(newRange);
                                                }*/
                                                var plateLabel = crossingHash.name + "-" + ypgSetLabelHash[ypgsetNum] + "-1";
                                                Ext.getCmp("platePrefixId").setValue(plateLabel);
                                            }
                                        }
                                    }
                                },
                                {
                                    id: 'thisProgenyRangeId',
                                    fieldLabel: 'Progeny range',
                                    value: ""
                                },
                                {
                                    id: 'thisProgenyGenotypeId',
                                    fieldLabel: 'Progeny genotype',
                                    width: 350,
                                    value: "SPS2:EGFP:natMX4 HO::HYG gal7d0::kanMx4"
                                },
                                {
                                    id: 'thisProgenyDateFrozenId',
                                    fieldLabel: 'Progeny DateFrozen',
                                    value: ""
                                },
                                {
                                    id: 'thisProgenyCommentId',
                                    fieldLabel: 'Progeny comment',
                                    width: 350,
                                    value: "YPRaff (2%) + 0.05% galactose + Antimycin A media"
                                },
                                {
                                    id: 'strainsPerPlateId',
                                    fieldLabel: 'Strains per plate',
                                    value: '96'
                                },
                                {
                                    id: 'platePrefixId',
                                    fieldLabel: 'Batch-Initial Plate Num' ,
                                    value: crossingHash.name + "-A-1" ,
                                    listeners: {
                                        render: function(c) {
                                            Ext.QuickTips.register({
                                                target: c,
                                                title: '',
                                                text: 'For 2nd, 3rd, ... progeny sets,include the iteration in the plate label, ie YCR12-B-1, with B standing for 2nd iteration'
                                            });
                                        }
                                    }
                                },
                                {
                                    id: 'tetradStrainCountId',
                                    value: '4',
                                    fieldLabel: 'Strains per Tetrad'
                                }
                        ]});
                   var  myWin = new Ext.Window({
                layout:'fit',
                id: 'ycrypgwinId',
                width:500,
                height:500,
                items: ycrYpgForm,
                buttons: [{
                    text:'Submit',
                    handler: function() {
                        var progenyCt = Ext.getCmp("thisProgenyCountId").getValue();
                        var newRange = Ext.getCmp("thisProgenyRangeId").getValue();
                        var genotype = Ext.getCmp("thisProgenyGenotypeId").getValue();
                        var comment = Ext.getCmp("thisProgenyCommentId").getValue();
                        var datefrozen = Ext.getCmp("thisProgenyDateFrozenId").getValue();
                        var spp = Ext.getCmp("strainsPerPlateId").getValue();
                        var tsc = Ext.getCmp("tetradStrainCountId").getValue();
                        var contact = LoggedInUser.userUri.split("/users/")[1];
                        var plateName = Ext.getCmp("platePrefixId").getValue();
                        if (trim(progenyCt) == ""){
                            Ext.Msg.alert("Progeny Count field can not be blank");
                            return;
                        }
                        if (trim(genotype) == ""){
                            Ext.Msg.alert("Genotype field can not be blank");
                            return;
                        }
                        if (trim(datefrozen) == ""){
                            Ext.Msg.alert("Date Frozen field can not be blank");
                            return;
                        }
                        if (trim(spp) == "" || trim(tsc) == ""){
                            Ext.Msg.alert("Strains Per Plate/Tetrad fields can not be blank");
                            return;
                        }
                        if (trim(plateName) == ""){
                            Ext.Msg.alert("Initial Plate name can not be blank");
                            return;
                        }
                        if (trim(comment) == ""){
                            Ext.Msg.alert("Comments field can not be blank");
                            return;
                        }
                        var cgiUrl = "/cgi-bin/loadypg?ycr="
                                        + crossingHash.name + "&pa="
                                        + crossingHash.parentA + "&pb="
                                        + crossingHash.parentAlpha + "&pc="
                                        + progenyCt + "&pgt="
                                        + genotype + "&pcmt="
                                        + comment + "&pdf="
                                        + datefrozen +
                                        "&ps="+ newRange.split(":")[0]
                                        + "&spp="  + spp + "&spt="  + tsc + "&ipn="  + plateName + "&ct="  + contact;
                        Ext.Ajax.request({
                        url: cgiUrl,
                        method: "GET",
                        success: function(response) {
                                var resp = Ext.util.JSON.decode(response.responseText);
                                if (resp.status == '200'){
                                    var newmax = Ext.getCmp("thisProgenyRangeId").getValue().split(":")[1];
                                    limsadmin_obj.limsadminYpgMaxNum = newmax;
                                    limsadmin_obj.limsadminYpgCount= newmax;
                                    postSolrUpdates(limsadmin_obj, function(){
                                        Ext.Msg.alert('Info', "Progeny set is submitted, a status email will be sent");
                                        var existingProgenyCt = Ext.getCmp("progenyCountId").getValue();
                                        Ext.getCmp("progenyCountId").setValue(parseInt(progenyCt) + parseInt(existingProgenyCt));
                                        var existingRange = Ext.getCmp("progenyRangeId").getValue();
                                        progenyCt = parseInt(progenyCt) + parseInt(existingProgenyCt);
                                        Ext.getCmp("progenyRangeId").setValue(newRange);
                                        if (existingRange != undefined){
                                            var startNewRange = parseInt(newRange.split(":")[0]);
                                            var endOldRange = parseInt(existingRange.split(":")[1]);
                                            if (existingRange.indexOf(",") != -1 || existingRange.indexOf(":") != -1){
                                                Ext.getCmp("progenyRangeId").setValue(crossingHash.progenyRange + "," + newRange);
                                            }
                                        }
                                        Ext.getCmp("tetradCountId").setValue(parseInt(progenyCt)/parseInt(tsc));
                                        Ext.getCmp("ycrypgwinId").close();
                                        postCrossingStrain(false);
                                    });
                                }else{
                                    alert("Progeny generation submission failed, send this message to jake: " + cgiUrl + "\n" + resp)
                                }
                        },
                        failure: function() {
                            eventManager.fireStatusMessageEvent({ text: "Failed Getting LIMSAdmin annotations", level: "error" });
                    }
                });
                    }}]
                });
                myWin.show();})
                }}
                },
                {
                    id: 'viewCrossingProgenyButtonId',
                    name: 'updateCrossingProgenyButton',
                    text: 'View Progeny',
                    disabled: !createNew,
                    icon: "images/star.png",
                    cls:'x-btn-text-icon',
                    tooltip: 'View progeny',
                    listeners: {click:
                            function() {
                                Dudley.lims.YPGStrain.setSearchParam(crossingHash.name.replace(/ /, ""));
                                Dudley.lims.YPGStrain.setSearchOption("ypgCrossingRef");
                                Dudley.lims.YPGStrain.setYPGLoaded(false);
                                var ypgPanel = Dudley.lims.YPGStrain.getYPGPanelInst();
                                Dudley.lims.samplemgr.getHousingPanel().activate(ypgPanel);
                            }
                    }
                },
                /*{
                    text: 'SNPClassifications@IGV',
                    icon: "images/igv.png",
                    cls:'x-btn-text-icon',
                    disabled: !mergedSnp,
                    tooltip: 'Launches IGV with cross custom mutation sources, including unique SNPs',
                    listeners: {
                        render: function(c) {
                            Ext.QuickTips.register({
                                target: c,
                                title: '',
                                text: 'Button launches Integrated Genome Viewer for visualizing strain variations with reference'
                            });
                        },
                        click: function(c) {
                            Ext.MessageBox.prompt('Gene-Locus', 'Enter optional gene or locus(ie chrI:200-1000):', function(btn, text) {
                                if (text && text.length > 1) {
                                    var parsedLink = igvlink.split(crossingHash.YCGSKey1);
                                    igvlink = parsedLink[0] + crossingHash.YCGSKey1 + ":" + crossingHash.YCGSKey2 + "locuz:" + text + "/jnlp";
                                }
                                if (btn == "ok")
                                    window.open(igvlink, '_blank');
                            });
                        }
                    }
                }, */
                {
                    id: 'detailSpotlightYCRId',
                    disabled: !createNew,
                    text: 'Spotlight',
                    icon: "images/add-green.png",
                    cls:'x-btn-text-icon',
                    tooltip: 'Add to spotlight',
                    listeners: {
                        click: function() {
                            var selectedArray = [crossingHash.name, crossingHash.name, crossingHash.crossingAlias + " Parents: " + crossingHash.parentA + " " + crossingHash.parentAlpha];
                            sptlght.utils.SpotlightUtils.setSelectedRecord(selectedArray);
                            sptlght.utils.SpotlightUtils.setSource("ycr");
                            sptlght.utils.SpotlightUtils.handleAddToSpotlight();
                        }
                    }
                },{
                    id: 'detailViewSnpId',
                    disabled: disableSnp,
                    text: 'View SNPs',
                    icon: "images/igv.png",
                    cls:'x-btn-text-icon',
                    tooltip: 'Snp Table View',
                    listeners: {
                        click: function() {
                            prepSnps("I", 0, 10000, function(){
                                loadDataStore( responses['snps'], loadSnpTab("I:0-10000"));
                            });
                        }
                    }
                }
            ],
            buttons: buttons,
            items: [
                new Ext.form.FieldSet({
                    autoHeight: true,
                    border: false,
                    items: [
                        new Ext.form.TextField({
                            id: "crossingKeyId",
                            fieldLabel: "Key",
                            name: "crossingKey",
                            value: crossingHash.name,
                            width: 500,
                            readOnly: true,
                            allowBlank: false
                        }),
                        new Ext.form.TextField({
                            id: "crossingAliasId",
                            fieldLabel: "Alias",
                            name: "crossingAlias",
                            value: crossingHash.crossingAlias,
                            width: 500,
                            allowBlank: false
                        }),
                        new Ext.form.ComboBox({
                            store: crossingTypeStore,
                            id: 'crossingTypeId',
                            name: 'crossingType',
                            fieldLabel: 'Type',
                            displayField:'value',
                            valueField:'key',
                            typeAhead: true,
                            mode: 'local',
                            triggerAction: 'all',
                            value:crossingHash.crossingType,
                            forceSelection:true,
                            selectOnFocus:true,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'Indicates whether the cross is Natural Variation or xQTL'
                                    });
                                }
                            }
                        }),
                        new Ext.form.TextField({
                            id: "parentAId",
                            fieldLabel: "Parent A",
                            name: "parentA",
                            value: crossingHash.parentA,
                            width: 500,
                            allowBlank: false
                        }),
                        new Ext.form.TextField({
                            id: "parentAlphaId",
                            fieldLabel: "Parent Alpha",
                            name: "parentAlpha",
                            value: crossingHash.parentAlpha,
                            width: 500,
                            allowBlank: false
                        }),
                        {
                            layout: 'hbox',
                            width: 500,
                            fieldLabel: 'SNPs',
                            msgTarget: 'under',
                            items: [
                                {
                                    xtype: 'displayfield',
                                    value: '&nbsp;Unique:&nbsp;'
                                },
                                new Ext.form.TextField({
                                    id: "snpId",
                                    fieldLabel: "Unique SNPs",
                                    value: crossingHash.SNPs,
                                    width: 150,
                                    allowBlank: false,
                                    listeners: {
                                        render: function(c) {
                                            Ext.QuickTips.register({
                                                target: c,
                                                title: '',
                                                text: 'Displaying total unique number of SNPs of parentA and parentAlpha, use IGV to explore merged track'
                                            });
                                        }
                                    }
                                }),
                                {
                                    xtype: 'displayfield',
                                    value: '&nbsp;Duplicates:&nbsp;'
                                },
                                new Ext.form.TextField({
                                    id: "snpDupeId",
                                    fieldLabel: "Duplicated SNPs",
                                    value: crossingHash.SNPDupes,
                                    width: 150,
                                    allowBlank: false,
                                    listeners: {
                                        render: function(c) {
                                            Ext.QuickTips.register({
                                                target: c,
                                                title: '',
                                                text: 'Displaying total duplicated SNPs of parentA and parentAlpha'
                                            });
                                        }
                                    }
                                })
                            ]
                        },
                        {
                            layout: 'hbox',
                            width: 500,
                            fieldLabel: 'Progeny Info',
                            msgTarget: 'under',
                            items: [
                                {
                                    xtype: 'displayfield',
                                    value: '&nbsp;Count:&nbsp;'
                                },
                                new Ext.form.TextField({
                                    id: "progenyCountId",
                                    name: "progenyCount",
                                    value: crossingHash.progenyCount,
                                    width: 150,
                                    allowBlank: false
                                }),
                                {
                                    xtype: 'displayfield',
                                    value: '&nbsp;Range:&nbsp;'
                                },
                                new Ext.form.TextField({
                                    id: "progenyRangeId",
                                    fieldLabel: "Progeny Range",
                                    name: "progenyRange",
                                    value: crossingHash.progenyRange,
                                    width: 200,
                                    allowBlank: false
                                })
                            ]
                        },
                        new Ext.form.TextField({
                            id: "tetradCountId",
                            fieldLabel: "Tetrads",
                            value: crossingHash.tetradCount,
                            width: 500,
                            allowBlank: false
                        }),
                        new Ext.form.DateField({
                            id: "crossingDateId",
                            fieldLabel: "Crossing Date",
                            name: "crossingDate",
                            value: crossingHash.crossingDate,
                            size: 20,
                            allowBlank: true
                        }),
                        {
                            xtype:'htmleditor',
                            id:'crossingPlatesId',
                            value: crossingHash.crossingPlates,
                            fieldLabel:'Plates and Parents Position',
                            height:130,
                            anchor:'98%',
                            listeners: {
                                activate: function(e) {
                                    if (crossingHash.crossingPlates == undefined || crossingHash.crossingPlates == "") {
                                        e.execCmd('delete');
                                    }
                                }
                            }
                        },
                        {
                            xtype:'htmleditor',
                            id:'crossingNoteId',
                            value: crossingHash.crossingNote,
                            fieldLabel:'Comments ' + '<br><i><font size=-2>Relevant information about the strain not covered in other fields</font></i>',
                            height:100,
                            anchor:'98%',
                            listeners: {
                                activate: function(e) {
                                    if (crossingHash.crossingNote == undefined || crossingHash.crossingNote == "") {
                                        e.execCmd('delete');
                                    }
                                }
                            }
                        }
                    ]
                })
            ]
        });
        callback();
    }

    var responses = {network : null};
    function prepSnps(chr, start, end, callback){
            Ext.getDom("yo-form").innerHTML = "";
            Ext.getDom("sample-search-result-list").innerHTML = "";
            var response_check={data : null};
            function handleNetworkQuery(response) {
                    response_check['data'] = 1;
                    responses = {snps : null};
                    responses['snps'] = vq.utils.GoogleDSUtils.dataTableToArray(response.getDataTable());
                    if (Ext.getCmp("snpResultsCountId"))
                        Ext.getCmp("snpResultsCountId").setValue(responses['snps'].length);
                    loadDataStore(responses['snps']);
                    callback();
            }
             var querySql = "select parent1, parent2, chr, start, end, ref_seq, p1_seq, p2_seq, vtype, annotation where chr = '" + chr
                + "' and start >=" +start + " and end < " + end + " order by vtype ASC";
             var network_query = new google.visualization.Query("/google-dsapi-svc/addama/datasources/omics/nv_snps/query?tq=" + querySql);
             network_query.setQuery(querySql);
             var timer = new vq.utils.SyncDatasources(400,40,function() {return null;},response_check);
             timer.start_poll();
             network_query.send(handleNetworkQuery);
    }

    function loadDataStore(snpList){
       var data = snpList.map(function(row) {
            return {
                parent1:row.parent1,
                parent2:row.parent2,
                chr:row.chr,
                start:row.start,
                end:row.end,
                ref_seq:row.ref_seq,
                p1_seq:row.p1_seq,
                p2_seq:row.p2_seq,
                vtype:row.vtype,
                annotation:row.annotation
                };
            });
       currentDataTableData = data;
       Ext.StoreMgr.get('snp_grid_store').loadData(data);
    }

     function loadSnpTab(chrRange) {
            Dudley.lims.sequencingmgr.clearPane();
            var snpPanel = Ext.ComponentMgr.get('nvSnpPanelId');
            if ( snpPanel == null) {
                Dudley.lims.samplemgr.getHousingPanel().add({
                    title: 'NV SNPs',
                    id: 'nvSnpPanelId',
                    iconCls: 'tabs',
                    items: [
                        {
                            layout: 'hbox',
                            width: 800,
                            msgTarget: 'under',
                            items: [
                                new Ext.form.FieldSet({
                                    autoHeight: true,
                                    border: false,
                                    items: [
                                        {
                                            layout: 'hbox',
                                            width: 750,
                                            msgTarget: 'under',
                                            items: [
                                                {
                                                    xtype: 'displayfield',
                                                    value: '&nbsp;Chr:Start-End&nbsp;'
                                                },
                                                new Ext.form.TextField({
                                                    id: "chrSnpId",
                                                    width: 120,
                                                    allowBlank: false,
                                                    value: chrRange,
                                                    listeners: {
                                                        render: function(c) {
                                                            Ext.QuickTips.register({
                                                                target: c,
                                                                title: '',
                                                                text: 'Enter chr:Start-End (ie chrI:100-10000)'
                                                            });
                                                        }
                                                    }
                                                }),
                                                {
                                                    xtype: 'displayfield',
                                                    value: '&nbsp;Gene&nbsp;'
                                                },
                                                new Ext.form.TextField({
                                                    id: "genecfid",
                                                    width: 70,
                                                    allowBlank: true,
                                                    listeners: {
                                                        render: function(c) {
                                                            Ext.QuickTips.register({
                                                                target: c,
                                                                title: '',
                                                                text: 'Common gene or systematic name both okay'
                                                            });
                                                        },
                                                        change: function(ov, nv){
                                                            nv = nv.toUpperCase();
                                                            function handleNetworkQuery(response) {
                                                                var generesp = vq.utils.GoogleDSUtils.dataTableToArray(response.getDataTable());
                                                                if (generesp == null || generesp.length == 0){
                                                                    Ext.Msg.alert("Invalid parameters");
                                                                }else{
                                                                    Ext.getCmp("chrSnpId").setValue(generesp[0]["chr"] + ":" +generesp[0]["start"] + "-" + generesp[0]["end"] );
                                                                    Ext.getCmp("snpResultsCountId").setValue(generesp.length);
                                                                }
                                                            }
                                                             var response_check={data : null};
                                                             var querySql = "select chr, start, end where systematic_name = '" + nv
                                                                + "' or common_name ='" +nv + "'";
                                                             var network_query = new google.visualization.Query("/google-dsapi-svc/addama/datasources/omics/yeast_gene_annotations/query?tq=" + querySql);
                                                             network_query.setQuery(querySql);
                                                             var timer = new vq.utils.SyncDatasources(400,40,function() {return null;},response_check);
                                                             timer.start_poll();
                                                             network_query.send(handleNetworkQuery);
                                                        }
                                                    }
                                                })
                                            ]
                                        },
                                        {
                                            layout: 'hbox',
                                            width: 750,
                                            msgTarget: 'under',
                                            style: {
                                                marginTop: '2px',
                                                marginBottom: '2px'
                                            },
                                            items: [
                                                {
                                                    xtype: 'displayfield',
                                                    value: '&nbsp;Total Results:&nbsp;'
                                                },
                                                {
                                                    xtype: 'displayfield',
                                                    id: 'snpResultsCountId',
                                                    value: responses['snps'].length
                                                }
                                            ]
                                        },
                                        {
                                            xtype: 'button',
                                            text: '&nbsp;Search&nbsp;',
                                            id: "searchClassificationsID",
                                            style: {
                                                marginTop: '2px',
                                                marginBottom: '2px'
                                            },
                                            listeners: {
                                            click: function() {
                                                var chrRange =  Ext.getCmp("chrSnpId").getValue();
                                                 var range = chrRange.split(":")[1].split("-");
                                                prepSnps(chrRange.split(":")[0], range[0], range[1], function(){
                                                    loadDataStore( responses['snps'], loadSnpTab());
                                                });
                                             }
                                            }
                                        }//end of button
                                    ]
                                })]
                        }
                    ],
                    keys: [
                        {
                            key: [Ext.EventObject.ENTER],
                            fn: function() {
                                Ext.ComponentMgr.get('searchClassificationsID').fireEvent('click');
                            }
                        }
                    ],
                    closable:true,
                    listeners: {
                        activate: function(p) {
                            Dudley.lims.samplemgr.getHousingPanel().activate(snpPanel);
                        }
                    }
                }).show();
            }

             var searchResultsGrid = new Ext.grid.GridPanel({
                        id: "snpSearchResultsId",
                        store: snpStore,
                        cm: new Ext.grid.ColumnModel({
                                    columns: [
                                        //{ header: "Parent1", width: 60,  id:'parent1', dataIndex:'parent1',groupName:'Snp'},
                                        //{ header: "Parent2", width: 60,  id:'parent2', dataIndex:'parent2',groupName:'Snp'},
                                        { header: "Chr", width: 40,  id:'chr', dataIndex:'chr',groupName:'Snp'},
                                        { header: "Start", width: 50,  id:'start', dataIndex:'start',groupName:'Snp'},
                                        { header: "End", width: 70,  id:'end', dataIndex:'end',groupName:'Snp'},
                                        { header: "RefSeq", width: 60,  id:'ref_seq', dataIndex:'ref_seq',groupName:'SnpSeq'},
                                        { header: "P1Seq", width: 125,  id:'p1_seq', dataIndex:'p1_seq',groupName:'SnpSeq'},
                                        { header: "P2Seq", width: 125,  id:'p2_seq', dataIndex:'p2_seq',groupName:'SnpSeq'},
                                        { header: "Type", width: 80,  id:'vtype', dataIndex:'vtype',groupName:'Snp'},
                                        { header: "Gene Info", width: 250,  id:'annotation', dataIndex:'annotation',groupName:'Snp'}
                                    ],
                                    defaults: {
                                                  sortable: true,
                                                  width: 100
                                                  }
                                     }),
                        stripeRows: true,
                        autoHeight: true,
                        width: 825,
                        title: 'YO490_YO512 Nonsynonymous Mutations - double click cell to expand, right click row to launch GBrowseSyn' ,
                        renderTo: "sample-search-result-list",
                        tbar: [
                                {
                                    id: 'crossing2CSVId',
                                    text: 'ExportSNP2CSV',
                                    icon: "images/check-green.png",
                                    cls:'x-btn-text-icon',
                                    tooltip: 'Export search results to csv',
                                    listeners: {click:
                                            function() {
                                                Dudley.lims.Crossing.snpToCSV(currentDataTableData, "SNPResults.csv");
                                            }
                                    }
                                }
                            ],
                            listeners: {
                                celldblclick: function(grid, rowIndex, columnIndex, e){
                                    var row = grid.getStore().getAt(rowIndex);
                                    var cid = grid.getColumnModel().columns[columnIndex].id;
                                    var sval = row.data[cid];
                                    Ext.MessageBox.alert(cid, sval);
                                },
                                rowcontextmenu:onGbrowseSynMessageContextMenu
                            }
              });
        }

    function onGbrowseSynMessageContextMenu(grid, rowIndex, e) {
            var row = grid.getStore().getAt(rowIndex);
            var region = chrhash[row.data["chr"]] + ":" + (parseInt(row.data["start"]) - 5000) + ".." + (parseInt(row.data["end"]) + 5000);
            var gbsynMenu = sptlght.utils.SpotlightUtils.getGbrowseSynMenu(region);
            e.preventDefault();
            e.stopEvent();
            var coords = e.getXY();
            gbsynMenu.showAt([coords[0], coords[1]]);
    }

    function renderCrossingDetails(g) {
        var searchResultsButton = Ext.getCmp("showCrossingSearchResultsId");
        searchResultsButton.enable();
        crossingHash = new Object();
        if (g != null) {
            populateCrossingJson(crossingHash, g);
        } else {
            populateSingleCrossingViaSearch(crossingHash, myCrossingData[0]);
        }
        var resourceUri = "/addama-rest/dudley-sample/path/datasource/YCR/" + crossingHash.name;
        Ext.Ajax.request({
            url: resourceUri + "/mayUpdate",
            method: "GET",
            params: {
                "user_uri": LoggedInUser.userUri
            },
            success: function() {
                loadCreateCrossingStrain(crossingHash, function() {
                    crossingFormRender();
                });
            },
            failure: function() {
                eventManager.fireStatusMessageEvent({ text: "Read only access allowed", level: "info" });
                loadCreateCrossingStrain(crossingHash, function() {
                    crossingFormRender();
                });
            }
        });
    }

    function renderCrossingSearchResult() {
        if (myCrossingData.length == 1) {
            renderCrossingDetails(null);
            return;
        }
        Ext.getDom("yo-panel").innerHTML = "";
        Ext.getDom("yad-panel").innerHTML = "";
        Ext.getDom("yo-form").innerHTML = "";

        var searchResultsButton = Ext.getCmp("showCrossingSearchResultsId");
        if (searchResultsButton != null || searchResultsButton != undefined) {
            searchResultsButton.disable();
        }
        pagingBar = new Ext.PagingToolbar({
            pageSize: 25,
            store: crossingStore,
            displayInfo: true,
            displayMsg: 'Displaying strains {0} - {1} of {2}',
            emptyMsg: "No strains to display"
        });
        var searchResultsGrid = new Ext.grid.GridPanel({
            id: "crossingSearchResultsId",
            store: crossingStore,
            columns: getCrossingSearchColumnHeaders(),
            stripeRows: true,
            autoHeight: true,
            width: 825,
            title: 'Cross ' + "<a href='/addama-rest/dudley/path/Documents/Cross%20Information/TetradDissectionPipeline.docx' target='_blank'>Tetrad Dissection Pipeline Guide</a>",
            renderTo: "sample-search-result-list",
            tbar: [
                {
                    id: 'crossing2CSVId',
                    text: 'Export2CSV',
                    icon: "images/check-green.png",
                    cls:'x-btn-text-icon',
                    tooltip: 'Export search results to csv',
                    listeners: {click:
                            function() {
                                Dudley.lims.Crossing.toCSV(myCrossingData, "YCRSearchedResults.csv");
                            }
                    }
                }
            ],
            bbar: pagingBar
        });
        searchResultsGrid.on("celldblclick", function (g, ri, ci, e) {
            renderCrossingDetails(g);
        });
        searchResultsGrid.on("rowcontextmenu", onMessageContextMenu);
    }

    function onMessageContextMenu(grid, rowIndex, e) {
        var activePage = Math.ceil((pagingBar.cursor + pagingBar.pageSize) / pagingBar.pageSize);
        var realIndex = (activePage - 1) * pagingBar.pageSize + rowIndex;
        sptlght.utils.SpotlightUtils.setSelectedRecord(crossingStore.allData.items[realIndex].json);
        sptlght.utils.SpotlightUtils.setSource("ycr");
        e.preventDefault();
        e.stopEvent();
        var coords = e.getXY();
        spotlightMenu.showAt([coords[0], coords[1]]);
    }

    function crossingFormRender() {
        Dudley.lims.samplemgr.getHousingPanel().activate(crossingPanel);
        Ext.getDom("sample-search-result-list").innerHTML = "";
        Ext.getDom("yo-form").innerHTML = "";
        crossingForm.render("yo-form");
    }

    function setCrossingAdmin(jsonObj){
        	limsadmin_obj =  jsonObj;
        	crossingCount = jsonObj.limsadminCrossingCount;
            crossingMaxNum = jsonObj.limsadminCrossingCount;
            crossingHash = null;
            Ext.getCmp("showCrossingSearchResultsId").enable();
                            loadCreateCrossingStrain(crossingHash, function() {
                                Ext.getDom("sample-search-result-list").innerHTML = "";
                                Ext.getDom("yo-form").innerHTML = "";
                                crossingForm.render("yo-form");
                            });
         }

    return {
        initCrossing: function(failedCB) {
            initCrossingStore(failedCB, function() {
                eventManager.fireStatusMessageEvent({ text: "Finishing init Crossing Store", level: "info" });
            });
        },
        getCrossingPanel: function() {
            loadCrossingPanel();
            return crossingPanel;
        },
        getCrossingStore: function() {
            return crossingStore;
        },
        setCrosssingLoaded: function(boo) {
            crossingLoaded = boo;
        },
        setCrossingSearchParams: function(myParam, myOption) {
            searchInput = myParam;
            searchOption = myOption;
        },
        getCrossingLoaded: function() {
            return crossingLoaded;
        },
        loadCrossingSearch: function() {
            goSearch(0, searchInput, searchOption);
        },
        loadNewCrossing: function() {
            Ext.getDom("yo-form").innerHTML = "";
            if (LoggedInUser.userUri == "/addama-users/users/public@systemsbiology.org") {
                Ext.Msg.alert("warning", "You not have permission to create new crossings");
            } else {
                getSolrLimsAdmin(setCrossingAdmin);
            }
        },
        loadSearchResult: function() {
            Ext.getDom("sample-search-result-list").innerHTML = "";
            renderCrossingSearchResult();
        },
        snpToCSV: function(currentData, csvName){
            var csvText = "type,chr,start, end, ref_seq,490_seq,512_seq, annotation" + breakDelimiter;
            for (var r = 0; r < currentData.length; r++){
                 csvText = csvText + "" + currentData[r].vtype + "," + currentData[r].chr + "," + currentData[r].start + "," + currentData[r].end
                 + "," + currentData[r].ref_seq + "," + currentData[r].p1_seq + "," + currentData[r].p2_seq +  "," + currentData[r].annotation + breakDelimiter;
            }
             export2Csv(csvName, csvText, "SNP2Csv");
        },
        toCSV: function(myData, csvname) {
            var csvText = "ycrKey,ycrAlias,ycrParentA,ycrParentAlpha,ycrProgenyCt,ycrProgenyRange,ycrTetradCt,ycrDate,ycrSnps,ycrSnpDupes,ycrPlates,ycrNotes,ycrIGV,ycrYCGSKeys,ycrYCGSKey1,ycrYCGSKey2" + breakDelimiter;
            myData.sort(function(a, b) {
                return a[0] - b[0];
            });
            for (var c = 0; c < myData.length; c++) {
                var cArray = myData[c];
                for (var ci = 0; ci < cArray.length; ci++) {
                    if (cArray[ci] == undefined || cArray[ci] == null) {
                        cArray[ci] = "";
                    }
                    cArray[ci] = cArray[ci] + "";                                        
                    cArray[ci] = cArray[ci].replace(/'/g, "");
                    cArray[ci] = '"' + cArray[ci] + '"';
                    cArray[ci] = cArray[ci].replace(/YKR /, "YKR");
                    cArray[ci] = cArray[ci].replace(/YCR /, "YCR");
                    cArray[ci] = cArray[ci].replace(/YPG /g, "YPG");
                    cArray[ci] = cArray[ci].replace(/YO /, "YO");
                    cArray[ci] = cArray[ci].replace(/YAD /, "YAD");
                }
                csvText = csvText + "" + cArray[1] + "," + cArray[2] + "," + cArray[3] + "," + cArray[4] + "," + cArray[5] + "," + cArray[9]
                        + "," + cArray[16] + "," + cArray[6] + "," + cArray[14] + "," + cArray[15]
                        + "," + cArray[8] + "," + cArray[7] + "," + cArray[10] + "," + cArray[11] + "," + cArray[12] + "," + cArray[13] + breakDelimiter;
            }
            export2Csv(csvname, csvText, "crossing2Csv");
        },
        setArrayData: function(data) {
            myCrossingData = data;
         }
    };
}();
